import React, { useState, useEffect, useRef, Fragment } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { PlusOutlined } from '@ant-design/icons';
import { Button, DatePicker, Divider, Row, Col, Input, Popconfirm } from 'antd';
import ProForm, { ProFormDigit, ProFormFieldSet, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import {
  getGoodsListByPage,
  getCategoryListByPage,
  getGoodsSpecsList,
  addStocks,
  adjustStocks,
  getSpecsBatchList,
  getSupplierList,
  batchAdjustStocks
} from '@/services/stock-goods/api';
import { getBatchNo } from '@/services/common/api';
import { formatDate, getDateValue, isNull, MsgType, showMsg } from '@/utils/utils';
import type { FormInstance } from 'antd';
import ProTable from '@ant-design/pro-table';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import PermissionControl from '@/components/PermissionControl';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import './style.less';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import { history, useModel } from 'umi';
import { subtractDays, currentDate } from '@/utils/utils';


interface DetailProps {
  location?: any;
}

const Detail: React.FC<DetailProps> = (props) => {
  const formRef = useRef<FormInstance>();
  const formRef1 = useRef<FormInstance>();
  const formRef2 = useRef<FormInstance>();
  const methodRef = useRef<FormInstance>();

  const searchFormRef = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();
  const initSpecColumns: ProColumns<STOCKGOODSAPI.GoodsSpecsItem>[] = [
    {
      title: '规格编号',
      dataIndex: 'specs_no',
      search: false,
      width: 60,
    },
    {
      title: '计量单位',
      dataIndex: 'unit',
      search: false
    },
    {
      title: '销售价',
      dataIndex: 'selling_price',
      align: 'right',
      valueType: 'money',
      search: false
    },
    {
      title: '库存',
      dataIndex: 'inventory',
      align: 'right',
      search: false
    },
    {
      title: '预警值',
      dataIndex: 'warn_inventory',
      align: 'right',
      search: false
    },
    {
      title: '待出库',
      dataIndex: 'wait_inventory',
      align: 'right',
      search: false
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        N: '正常',
        D: '已作废'
      },
      search: false
    }
  ];
  // 记录套用规格模板后的列定义
  const [specColumns, setSpecColumns] = useState<ProColumns<STOCKGOODSAPI.GoodsSpecsItem>[]>(initSpecColumns);

  const columns2: ProColumns<STOCKGOODSAPI.BatchItem>[] = [
    {
      title: '批次编号',
      dataIndex: 'batch_id'
    },
    {
      title: '批次创建时间',
      dataIndex: 'create_date',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        return (<ProFormFieldSet>
          <DatePicker style={{ width: '100%' }} />
          <span style={{ padding: '0 5px' }}>-</span>
          <DatePicker style={{ width: '100%' }} />
        </ProFormFieldSet>
        );
      }
    },
    {
      title: '批次存量',
      dataIndex: 'inventory',
      align: 'right',
      search: false
    },
    {
      title: '供应商名称',
      dataIndex: 'supplier',
      search: false
    },
    {
      title: '协议进货价',
      dataIndex: 'agree_price',
      valueType: 'money',
      align: 'right',
      search: false
    },
    {
      title: '进货折扣',
      dataIndex: 'purchase_discount',
      align: 'right',
      search: false
    },
    {
      title: '实际进货价',
      dataIndex: 'purchase_price',
      valueType: 'money',
      align: 'right',
      search: false
    }
  ]
  // 选中的规格行
  const [currentRow, setCurrentRow] = useState<STOCKGOODSAPI.GoodsSpecsItem>({});

  // 选中行
  const [selectBatch, setSelectBatch] = useState<STOCKGOODSAPI.BatchItem>({});

  // 库存调整选中的批次行
  const [selectedBatchIds, setSelectedBatchIds] = useState<React.Key[]>([]);

  // 商品列表
  const [goodsList, setGoodsList] = useState<STOCKGOODSAPI.GoodsItem[]>([]);

  // 分类列表
  const [classList, setClassList] = useState<STOCKGOODSAPI.CategoryItem[]>([]);

  // 商品规格列表
  const [goodsSpecsList, setGoodsSpecsList] = useState<STOCKGOODSAPI.GoodsSpecsItem[]>([]);

  // 调整方式
  const [adjustMethod, setAdjustMethod] = useState<string>('add');

  const [total, setTotal] = useState<number>(0);

  // 批次号
  const [batchNo, setBatchNo] = useState<string>('');

  // 搜索参数
  const [searchParams, setSearchParams] = useState<any>({});

  const [submitLoading, setSubmitLoading] = useState<boolean>(false);

  // 供应商
  const [supplier, setSupplier] = useState('');
  const [supplierList, setSupplierList] = useState([]);

  const [isWarning, setIsWarning] = useState(false); // 实际进货价大于销售价的时候，给个提示
  const [curGoodid, setCurGoodid] = useState('');

  const { initialState } = useModel('@@initialState');

  // 获取商品列表
  const fetchGoodsList = async (class_id?: string) => {
    try {
      const data: STOCKGOODSAPI.GoodsItemList = await getGoodsListByPage({
        current: 1,
        pageSize: 10000,
        class_id,
        scope: 'B',
        goods_status: 'all',
      });
      setGoodsList(data.record_list || []);
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  // 查询商品规格
  const fetchGoodsSpecsList = async (goods_id?: string, current = 1, pageSize = 10) => {
    try {
      const data: STOCKGOODSAPI.GoodsSpecsItemList = await getGoodsSpecsList({
        goods_id,
        current,
        pageSize
      });
      setCurGoodid(goods_id);
      // 规格模板数据应用
      data.record_list?.forEach(item => {
        const valObj = item.template_value || {};
        Object.keys(valObj).forEach(key => {
          item[key] = valObj[key];
        });
      });
      setGoodsSpecsList(data.record_list || []);
      setTotal(data.sum_record_num || 0);
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  // 获取批次号
  const fetchBatchNo = async () => {
    try {
      // 批次号
      const data = await getBatchNo();
      setBatchNo(data.jrn_no);
      formRef.current?.setFieldsValue({
        batch_id: data.jrn_no
      });
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  // 查询供应商列表
  const getSupplier = () => {
    getSupplierList().then((res) => setSupplierList(res.record_list || []));
  }

  useEffect(() => {
    // 商品分类
    getCategoryListByPage({ current: 1, pageSize: 10000 }).then((data: STOCKGOODSAPI.CategoryItemList) => {
      setClassList(data.record_list || []);
    }).catch(error => {
      showMsg(error?.data?.errmsg);
    });
    fetchGoodsList();
    getSupplier();
    // fetchBatchNo();
  }, []);

  const addSupplier = () => {
    supplierList.push({ supplier });
    setSupplierList(Object.assign([], supplierList))

    setTimeout(() => {
      formRef.current?.setFieldsValue({
        supplier,
      })
    }, 100);
  }

  const renderSupplier = () => {
    const list1 = [];
    supplierList.map(item => {
      list1.push({
        label: item.supplier,
        value: item.supplier as string,
      })
    })
    // if (!isNull(record.class_id) && !inArray(categoryList, record.class_id, 'bol', 'class_id')) {
    //   list1.push({
    //     label: `${record.class_name}`,
    //     value: record.class_id,
    //     disabled: true,
    //   })
    // }
    return list1;
  }

  /**
   * 应用规格模板
   * @param value
   */
  const applySpecTemplate = (template_conent: string[]) => {
    const specArr = template_conent.map(elem => (
      { title: elem, dataIndex: elem, formItemProps: { rules: [{ required: true, message: elem + '是必填项' }] }, isSpec: true }
    ));
    const columns = [...initSpecColumns];
    columns.splice(1, 0, ...specArr);
    setSpecColumns(columns);
  };

  return (
    <PageContainer
      title="调整库存" extra={<BreadcrumbDept />} breadcrumb={{}}
      className="adjust-stock-container" onBack={() => history.goBack()}
    >
      <div className="service-record">
        <div className="header">
          <div className="title">1. 选择商品规格</div>
        </div>

        <Divider style={{ margin: '10px 0' }} />

        <ProForm
          className="search-pro-form"
          formRef={searchFormRef}
          scrollToFirstError
          submitter={{
            searchConfig: {
              submitText: '查询'
            },
            resetButtonProps: {
              style: {
                display: 'none'
              }
            },
          }}
          onFinish={async (values) => {
            if (!values.goods_id) {
              showMsg('请选择商品', MsgType.INFO);
              return;
            }
            fetchGoodsSpecsList(values.goods_id, values.create_dept_code);
          }}
          layout='inline'>
          <ProForm.Group>
            <ProFormSelect
              label="商品分类"
              name="class_id"
              showSearch
              width={200}
              placeholder="输入或选择分类"
              options={classList.map(item => {
                return {
                  label: item.class_name as string,
                  value: `${item.class_id}|${item.class_py}`
                }
              })}
              fieldProps={{
                filterOption: false,
                onChange: (value: string) => {
                  searchFormRef.current?.setFieldsValue({
                    goods_name: null,
                    goods_id: null,

                  });
                  const class_id = value && value.split('|')[0];
                  fetchGoodsList(class_id);
                  setGoodsSpecsList([]);
                  setSpecColumns(initSpecColumns);
                  actionRef.current?.reload();
                }
              }}
            />
            <ProFormSelect
              label="商品名称"
              name="goods_name"
              placeholder="输入或选择商品"
              width={200}
              options={goodsList.map(item => {
                return {
                  label: `【${item.brand_name}】${item.goods_name}（${item.goods_py}）`,
                  value: `${item.goods_id}|${item.goods_name}|${item.brand_name}`,
                  template_content: item.template_content
                }
              })}
              fieldProps={{
                showSearch: true,
                onChange: (value, opt) => {
                  searchFormRef.current?.setFieldsValue({
                    goods_id: isNull(value) ? '' : value.split('|')[0],
                  })
                  //套用规格模板
                  applySpecTemplate(opt ? opt['template_content'] ?? [] : initSpecColumns);
                  setGoodsSpecsList([]);
                  setAdjustMethod('add');
                  methodRef.current?.setFieldsValue({ adjust_method: 'add' });
                  actionRef.current?.reload();
                }
              }}
            />
            <ProFormText
              label="商品编号"
              readonly
              name="goods_id"
              width={200}
            />
          </ProForm.Group>
        </ProForm>

        <ProTable
          actionRef={actionRef}
          rowKey="specs_id"
          rowClassName={record => record.inventory < record.warn_inventory ? 'update-bg' : ''}
          search={false}
          bordered
          options={false}
          rowSelection={{
            type: 'radio',
            onChange: (rowKey, seletedRow) => {
              setCurrentRow(seletedRow[0]);
              setSearchParams({
                specs_id: seletedRow[0].specs_id
              });
            }
          }}
          columns={specColumns}
          pagination={{
            total,
            current: 1,
            pageSize: 10,
            onChange: (page, pageSize) => fetchGoodsSpecsList(curGoodid, page, pageSize)
          }}
          dataSource={goodsSpecsList} />
      </div>

      <div className="service-record service-record1">
        <div className="header">
          <div className="title">2. 调整库存</div>
        </div>

        <Divider style={{ margin: '10px 0' }} />

        <ProForm formRef={methodRef} submitter={false} className="adjust-method-pro-form" layout="horizontal">
          <ProFormRadio.Group
            label="调整方式"
            name="adjust_method"
            width='lg'
            initialValue={"add"}
            fieldProps={{
              onChange: (e: any) => {
                const value = e.target.value;
                setAdjustMethod(value);
                if (value === 'add') {
                  formRef.current?.setFieldsValue({
                    batch_id: batchNo
                  });
                } else {
                  // setTimeout(() => {
                  //   formRef2.current?.setFieldsValue({
                  //     create_date: [subtractDays(30), '', currentDate()]
                  //   })
                  // }, 500);
                }
              }
            }}
            options={
              [
                {
                  label: '新增入库',
                  value: 'add'
                },
                {
                  label: '库存调整',
                  value: 'adjust',
                  disabled: !currentRow.specs_id
                },
                {
                  label: '批量库存调整',
                  value: 'batch-adjust',
                  style: { display: initialState?.currentUser?.dept_type === 'Y' ? undefined : 'none' }
                }
              ]
            }
          />
        </ProForm>

        {
          adjustMethod === 'add' && (
            <ProForm
              className="order-pro-form"
              layout="horizontal"
              formRef={formRef}
              submitter={{
                render: () => <div style={{ textAlign: 'right' }}>
                  <PermissionControl action_id="200203006">
                    {
                      isWarning ?
                        <Popconfirm
                          title="检测到进货价大于等于商品销售价格，是否确认提交?"
                          placement='bottomRight'
                          onConfirm={() => formRef.current?.submit()}
                          okText='确认'
                          cancelText='再想想'
                        >
                          <Button
                            type='primary'
                            loading={submitLoading}
                          >提交审核</Button>
                        </Popconfirm>
                        :
                        <Button
                          type='primary'
                          loading={submitLoading}
                          onClick={() => formRef.current?.submit()}>提交审核</Button>
                    }
                  </PermissionControl>
                </div>,
              }}
              onFinish={async (values) => {
                if (!currentRow.specs_id) {
                  showMsg('请选择商品规格', MsgType.INFO);
                  return;
                }
                try {
                  if (submitLoading) {
                    return;
                  }
                  setSubmitLoading(true);
                  values = Object.assign({}, values, { specs_id: currentRow.specs_id });
                  await addStocks(values);
                  showMsg('已提交', MsgType.SUCCESS);
                  formRef.current?.resetFields();
                  setSubmitLoading(false);
                  formRef.current?.setFieldsValue({
                    batch_id: null
                  })
                  setIsWarning(false);
                } catch (error) {
                  console.log('error', error);
                  showMsg(error?.data?.errmsg);
                  setSubmitLoading(false);
                }
              }}>
              <ProForm.Group>
                <div style={{ display: 'flex' }} className='batchid'>
                  <ProFormText
                    label="批次编号"
                    width='sm'
                    name="batch_id"
                    rules={
                      [
                        {
                          required: true
                        }
                      ]
                    }
                    initialValue={batchNo}
                    fieldProps={{
                      readOnly: true,
                      suffix: <Button
                        onClick={() => {
                          fetchBatchNo();
                        }}
                        type="primary">生成批次号</Button>
                    }
                    }
                  />

                </div>

                {/* <ProFormText
                label="供应商"
                name="supplier"
                width='sm'
                rules={
                  [
                    {
                      required: true
                    }
                  ]
                }
              /> */}
                <ProFormSelect
                  rules={
                    [
                      {
                        required: true,
                        message: '请输入或选择供应商'
                      }
                    ]
                  }
                  label="供应商"
                  placeholder="请输入或选择供应商"
                  width="sm"
                  name="supplier"
                  style={{ width: '100%' }}
                  options={renderSupplier()}
                  fieldProps={{
                    optionFilterProp: 'children',
                    filterOption: (input, option) => {
                      return (option?.label?.toLowerCase()).includes(input.toLowerCase())
                    },
                    dropdownRender: (menu) => {
                      return <div>
                        {menu}
                        <Divider style={{ margin: '4px 0' }} />
                        <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'nowrap', padding: 8 }}>
                          <Input
                            style={{ flex: 'auto', height: 24 }}
                            value={supplier}
                            onPressEnter={addSupplier}
                            onChange={(event) => setSupplier(event.target.value)}
                          />
                          <a style={{ flex: 'none', padding: '8px', display: 'block', cursor: 'pointer' }} onClick={addSupplier}>
                            <PlusOutlined /> 新增供应商
                          </a>
                        </div>
                      </div>
                    },
                    onSelect: async (val, opt) => {
                      console.log('opt', val, opt)
                      const value = opt.class_name;
                      setSupplier(value);
                    },
                    showSearch: true
                  }}
                />

                <ProFormDigit
                  label="入库数量"
                  name="inventory"
                  width='sm'
                  rules={
                    [
                      {
                        required: true
                      }
                    ]
                  }
                />
              </ProForm.Group>
              <ProForm.Group>
                <div style={{ display: 'flex' }}>
                  <ProFormDigit
                    label="协议进货价"
                    name="agree_price"
                    width='sm'
                    rules={
                      [
                        {
                          required: true
                        }
                      ]
                    }
                    fieldProps={
                      {
                        onChange: (value) => {
                          const purchase_discount = formRef.current?.getFieldValue('purchase_discount')
                          if (purchase_discount) {
                            const val = parseFloat(Number(value) * purchase_discount).toFixed(2);
                            formRef.current?.setFieldsValue({
                              purchase_price: val
                            })
                            setIsWarning(val >= parseFloat(currentRow.selling_price));
                          }
                        },
                        precision: 2
                      }
                    }
                  />
                </div>

                <ProFormDigit
                  label="进货折扣"
                  name="purchase_discount"
                  width='sm'
                  rules={
                    [
                      {
                        required: true
                      },
                      {
                        validator: async (_, value) =>
                          value > 0 && value <= 1 ? Promise.resolve() : Promise.reject(new Error('进货折扣不能为0')),
                        message: '进货折扣为0.01-1之间',
                      },
                    ]
                  }
                  fieldProps={
                    {
                      onChange: (value) => {
                        const agree_price = formRef.current?.getFieldValue('agree_price')
                        if (Number.isFinite(parseFloat(value)) && parseFloat(agree_price) > 0) {
                          let val = Number(agree_price * value).toFixed(2);
                          console.log('val', val, agree_price, value)
                          val = parseFloat(val) <= 0 ? '0.01' : parseFloat(value) > 1 ? agree_price : val;
                          console.log('val1', val);
                          formRef.current?.setFieldsValue({
                            purchase_price: val
                          })
                          setIsWarning(val >= parseFloat(currentRow.selling_price));
                        }
                      },
                      precision: 2
                    }
                  }
                />
                <ProFormDigit
                  label="实际进货价"
                  name="purchase_price"
                  width='sm'
                  rules={
                    [
                      {
                        required: true
                      },
                      {
                        validator: async (_, value) => {
                          const agree_price = formRef.current?.getFieldValue('agree_price')
                          if (Number.isFinite(parseFloat(value)) && parseFloat(agree_price) > 0) {
                            return value === 0 ? Promise.reject(new Error('实际进货价不能为0')) : Promise.resolve();
                          }
                          return Promise.resolve();
                        },
                        message: '实际进货价不能为0'
                      },
                      {
                        validator: async (_, value) => {
                          const agree_price = formRef.current?.getFieldValue('agree_price')
                          if (Number.isFinite(parseFloat(value)) && parseFloat(agree_price) > 0) {
                            return value <= agree_price ? Promise.resolve() : Promise.reject(new Error('实际进货价不能为0'));
                          }
                          return Promise.resolve();
                        },
                        message: '实际进货价不能大于协议进货价'
                      },
                    ]
                  }
                  // validateStatus={isWarning ? 'warning' : 'validating'}
                  // help={isWarning ? `销售价为￥${currentRow.selling_price}` : null}
                  fieldProps={
                    {
                      onChange: (value) => {
                        const agree_price = formRef.current?.getFieldValue('agree_price')
                        if (Number.isFinite(parseFloat(value)) && parseFloat(agree_price) > 0) {
                          let val = parseFloat(value / agree_price).toFixed(2);
                          if (value <= agree_price) {
                            val = parseFloat(val) <= 0 ? '0.01' : val;
                            formRef.current?.setFieldsValue({
                              purchase_discount: val,
                            })
                          } else {
                            formRef.current?.setFieldsValue({
                              purchase_discount: 1,
                            })
                          }
                          setIsWarning(value >= parseFloat(currentRow.selling_price));
                        }
                      },
                      precision: 2,

                    }
                  }
                />
              </ProForm.Group>
              <ProForm.Group>
                <ProFormText
                  label="入库说明"
                  name="explains"
                  width='sm'
                />
              </ProForm.Group>
            </ProForm>)
        }

        {
          adjustMethod === 'adjust' && <Fragment>
            <ProTable<any, { specs_id: string; create_date?: any[]; begin_date?: string; end_date?: string; } & COMMON.PageParams>
              rowKey="batch_id"
              className="batch-pro-table"
              bordered
              params={searchParams}
              formRef={formRef2}
              columns={columns2}
              search={{
                collapsed: false,
                collapseRender: () => { return null },
                optionRender: (searchConfig, formProps, dom) => {
                  return [
                    <PermissionControl key="search" action_id="200203000">
                      <Button
                        onClick={() => {
                          formProps.form?.submit();
                        }}
                        type="primary">
                        检索
                      </Button>
                    </PermissionControl>
                  ]
                }
              }}
              request={async (params) => {
                console.log(params);
                if (params.create_date) {
                  params.begin_date = isNull(params.create_date[0]) ? '' : formatDate(params.create_date[0], 'YYYYMMDD');
                  params.end_date = isNull(params.create_date[2]) ? '' : formatDate(params.create_date[2], 'YYYYMMDD');
                  if (params.create_date[0] && params.create_date[2]) {
                    if (getDateValue(params.create_date[0]) > getDateValue(params.create_date[2])) {
                      showMsg('批次创建结束时间不能早于开始时间', MsgType.INFO);
                      return {
                        data: [],
                        success: true,
                        total: 0
                      };
                    }
                  }
                } else {
                  params.begin_date = isNull(params.begin_date) ? '' : formatDate(subtractDays(30), 'YYYYMMDD');
                  params.end_date = isNull(params.end_date) ? '' : formatDate(currentDate(), 'YYYYMMDD');
                }
                params.specs_id = currentRow.specs_id as string;
                for (const prop in params) {
                  if (!params[prop]) {
                    delete params[prop];
                  }
                }
                delete params.create_date;
                console.log('params', params)
                try {
                  const data: any = await getSpecsBatchList(params);
                  return {
                    data: data.record_list,
                    success: true,
                    total: data.sum_record_num
                  };
                } catch (error) {
                  showMsg(error?.data?.errmsg);
                  return {
                    data: [],
                    success: true,
                    total: 0
                  };
                }
              }}

              rowSelection={{
                type: 'radio',
                onChange: (rowKey, seletedRow) => setSelectBatch(seletedRow[0]),
                getCheckboxProps: (record) => {
                  return {
                    disabled: record.status !== 'N'
                  }
                }
              }}
              options={false}

              pagination={{
                showQuickJumper: true
              }}
            />
            <ProForm
              className="adjust-pro-form"
              layout="horizontal"
              formRef={formRef1}
              submitter={{
                render: () => <div style={{ textAlign: 'right' }}>
                  <PermissionControl action_id="200203007">
                    <Button loading={submitLoading} type='primary' onClick={() => formRef1.current?.submit()}>提交审核</Button>
                  </PermissionControl>
                </div>,
              }}
              onFinish={async (values) => {
                if (!currentRow.specs_id) {
                  showMsg('请选择商品规格', MsgType.INFO);
                  return;
                }
                if (!selectBatch.batch_id) {
                  showMsg('请选择批次', MsgType.INFO);
                  return;
                }
                try {
                  if (submitLoading) {
                    return;
                  }
                  setSubmitLoading(true);
                  values = Object.assign({}, values, { batch_id: selectBatch.batch_id });
                  await adjustStocks(values);
                  showMsg('已提交', MsgType.SUCCESS);
                  setSubmitLoading(false);
                  // setTimeout(() => {
                  //   history.back();
                  // }, 1000);
                  formRef1.current?.resetFields();
                } catch (error) {
                  showMsg(error?.data?.errmsg);
                  setSubmitLoading(false);
                }
              }}>
              <Row gutter={24} style={{ marginTop: 8 }}>
                <Col span={8}>
                  <ProFormDigit
                    // labelCol={{ span: 7 }}
                    label="调整批次数量"
                    name="inventory"
                    // width='sm'
                    min={-99999999}
                    rules={[{ required: true }]}
                  />
                </Col>
                <Col span={8}>
                  <span className="warning">
                    <ExclamationCircleOutlined />
                    正数为增加对应批次存量，负数为减少对应批次存量
                  </span>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col span={8} className='tzyy'>
                  <ProFormTextArea
                    // labelCol={{ span: 7 }}
                    label='调整原因'
                    name="submit_explain"
                  // width='sm'
                  />
                </Col>
              </Row>
            </ProForm>
          </Fragment>
        }

        {
          adjustMethod === 'batch-adjust' && <Fragment>
            <ProTable<any, { specs_id: string; create_date?: any[]; begin_date?: string; end_date?: string; } & COMMON.PageParams>
              rowKey="batch_id"
              className="batch-pro-table"
              bordered
              params={searchParams}
              formRef={formRef2}
              columns={columns2}
              search={{
                collapsed: false,
                collapseRender: () => { return null },
                optionRender: (searchConfig, formProps, dom) => {
                  return [
                    <PermissionControl key="search" action_id="200203000">
                      <Button
                        onClick={() => {
                          formProps.form?.submit();
                        }}
                        type="primary">
                        检索
                      </Button>
                    </PermissionControl>
                  ]
                }
              }}
              request={async (params) => {
                console.log(params);
                if (params.create_date) {
                  params.begin_date = isNull(params.create_date[0]) ? '' : formatDate(params.create_date[0], 'YYYYMMDD');
                  params.end_date = isNull(params.create_date[2]) ? '' : formatDate(params.create_date[2], 'YYYYMMDD');
                  if (params.create_date[0] && params.create_date[2]) {
                    if (getDateValue(params.create_date[0]) > getDateValue(params.create_date[2])) {
                      showMsg('批次创建结束时间不能早于开始时间', MsgType.INFO);
                      return {
                        data: [],
                        success: true,
                        total: 0
                      };
                    }
                  }
                } else {
                  params.begin_date = isNull(params.begin_date) ? '' : formatDate(subtractDays(30), 'YYYYMMDD');
                  params.end_date = isNull(params.end_date) ? '' : formatDate(currentDate(), 'YYYYMMDD');
                }
                params.specs_id = currentRow.specs_id as string;
                for (const prop in params) {
                  if (!params[prop]) {
                    delete params[prop];
                  }
                }
                delete params.create_date;
                console.log('params', params)
                try {
                  const data: any = await getSpecsBatchList(params);
                  return {
                    data: data.record_list,
                    success: true,
                    total: data.sum_record_num
                  };
                } catch (error) {
                  showMsg(error?.data?.errmsg);
                  return {
                    data: [],
                    success: true,
                    total: 0
                  };
                }
              }}

              rowSelection={{
                type: 'checkbox',
                onChange: setSelectedBatchIds,
                getCheckboxProps: (record) => {
                  return {
                    disabled: record.status !== 'N'
                  }
                }
              }}
              options={false}

              pagination={{
                showQuickJumper: true
              }}
            />
            <ProForm
              className="adjust-pro-form"
              layout="horizontal"
              formRef={formRef1}
              submitter={{
                render: () => <div style={{ textAlign: 'right' }}>
                  <PermissionControl action_id="200203007">
                    <Button loading={submitLoading} type='primary' onClick={() => formRef1.current?.submit()}>提交审核</Button>
                  </PermissionControl>
                </div>,
              }}
              onFinish={async (values) => {
                if (!currentRow.specs_id) {
                  showMsg('请选择商品规格', MsgType.INFO);
                  return;
                }
                if (selectedBatchIds.length === 0) {
                  showMsg('请选择批次', MsgType.INFO);
                  return;
                }
                try {
                  if (submitLoading) {
                    return;
                  }
                  setSubmitLoading(true);
                  values = Object.assign({}, values, { specs_id: currentRow.specs_id, batch_ids: selectedBatchIds });
                  await batchAdjustStocks(values);
                  showMsg('已提交', MsgType.SUCCESS);
                  setSubmitLoading(false);
                  // setTimeout(() => {
                  //   history.back();
                  // }, 1000);
                  formRef1.current?.resetFields();
                } catch (error) {
                  showMsg(error?.data?.errmsg);
                  setSubmitLoading(false);
                }
              }}>
              <ProFormText name="batch_level" initialValue="1" hidden readonly />
              <Row gutter={24} style={{ marginTop: 8 }}></Row>
              <Row gutter={24}>
                <Col span={8}>
                  {/* <ProFormText name="supplier" label='供应商' /> */}
                  <ProFormSelect
                    label="供应商"
                    placeholder="请输入或选择供应商"
                    name="supplier"
                    style={{ width: '100%' }}
                    options={renderSupplier()}
                    fieldProps={{
                      optionFilterProp: 'children',
                      filterOption: (input, option) => {
                        return (option?.label?.toLowerCase()).includes(input.toLowerCase())
                      },
                      dropdownRender: (menu) => {
                        return <div>
                          {menu}
                          <Divider style={{ margin: '4px 0' }} />
                          <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'nowrap', padding: 8 }}>
                            <Input
                              style={{ flex: 'auto', height: 24 }}
                              value={supplier}
                              onPressEnter={addSupplier}
                              onChange={(event) => setSupplier(event.target.value)}
                            />
                            <a style={{ flex: 'none', padding: '8px', display: 'block', cursor: 'pointer' }} onClick={addSupplier}>
                              <PlusOutlined /> 新增供应商
                            </a>
                          </div>
                        </div>
                      },
                      onSelect: async (val, opt) => {
                        const value = opt.class_name;
                        setSupplier(value);
                      },
                      showSearch: true
                    }}
                    rules={[{ required: true }]}
                  />
                </Col>
                <Col span={8}>
                  <ProFormDigit name="ratio" label='调整系数' labelCol={{ flex: '0 0 max-content' }} rules={[{ required: true }]} />
                </Col>
                <Col span={8}>
                  <span className="warning">
                    <ExclamationCircleOutlined />
                    供应商、系数的修改仅对有剩余数量的批次生效
                  </span>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col span={8} className='tzyy'>
                  <ProFormTextArea
                    // labelCol={{ span: 7 }}
                    label='调整原因'
                    name="submit_explain"
                  // width='sm'
                  />
                </Col>
              </Row>
            </ProForm>
          </Fragment>
        }
      </div>
    </PageContainer>
  );
};
export default Detail;
